package com.sms.gateway.config;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import reactor.core.publisher.Mono;

@Configuration
public class GatewayFilterConfig {
    // 日志记录全局过滤器（Order值越小，执行优先级越高）
    @Bean
    @Order(-100)
    public GlobalFilter loggingFilter() {
        return (exchange, chain) -> {
            // 前置处理：记录请求开始时间和请求信息
            long startTime = System.currentTimeMillis();
            String method = exchange.getRequest().getMethod().name();
            String path = exchange.getRequest().getPath().value();
            System.out.printf("【请求日志】方法：%s，路径：%s，开始时间：%d%n", method, path, startTime);

            // 执行后续过滤器链
            return chain.filter(exchange)
                    // 后置处理：记录响应信息和耗时
                    .then(Mono.fromRunnable(() -> {
                        int statusCode = exchange.getResponse().getStatusCode().value();
                        long endTime = System.currentTimeMillis();
                        System.out.printf("【响应日志】路径：%s，状态码：%d，耗时：%dms%n",
                                path, statusCode, endTime - startTime);
                    }));
        };
    }
}
